import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Divider } from 'antd';
import { withRouter } from 'umi';
import moment, { isDate } from 'moment';
import prompt from '@/components/Prompt';
import StandardTable from '@/components/StandardTable';
import AntdInput from '@/components/AntdInput';
import AdSelect from '@/components/AdSelect';
import AntdForm from '@/components/AntdForm';
import AntdFormItem from '@/components/AntdFormItem';
import AntdDatePicker from '@/components/AntdDatePicker';
import FileReader from '@/components/FileReader';
import AntdSelectRegion from '@/components/AntdSelectRegion';
import SearchSelect from '@/components/SearchSelect';
import { allDictList } from '@/utils/constans';
import { queryDict, filterAddFile, filterDeteteFile, formatPrice } from '@/utils/common';
import { columnsDriver } from '@/pages/Common/common';
import {
    selectArchivesDetailAndInfo,
    allDispatchType,
    renderTableAdSelect,
    codes,
    DateMinus,
    columnsTrain,
} from './utils';
import styles from './archives.less';

const dateFormat = 'YYYY-MM-DD';

@connect(({ Archives, component, loading }) => ({
    dictObject: component.dictObject,
    pressureInfoList: Archives.pressureInfoList,
    trainInfoList: Archives.trainInfoList,
    loading: loading.effects[allDispatchType.incidentalInfo],
}))
@Form.create()
@withRouter
export default class PressureInfo extends Component {
    constructor(props) {
        super(props);
        const {
            form: { getFieldDecorator },
        } = props;
        this.state = {
            detailId: '',
            preData: {},
            trainPlace: props.isHK ? allDictList.pressure_placeHK : allDictList.archives_place,
        };
        this.commonParams = {
            getFieldDecorator,
        };
    }

    columns = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 50,
            render: (text, record, i) => {
                return <span>{i + 1}</span>;
            },
        },
        {
            title: '压夜地',
            dataIndex: 'address',
            width: 120,
            render: (text, record) => {
                const { dictObject, onlyRead, disabled } = this.props;
                const { trainPlace } = this.state;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`address-${record.id}`}
                            initialValue={text}
                            {...this.commonParams}
                            rules={[{ required: true }]}
                        >
                            <AdSelect
                                disabled={disabled}
                                isExist={true}
                                data={dictObject[trainPlace]}
                                payload={{ code: trainPlace }}
                                onChange={value => this.handleFieldChange(value, 'address', record.id)}
                            />
                        </AntdFormItem>
                    );
                }
                return renderTableAdSelect({
                    props: this.props,
                    value: text,
                    key: allDictList.archives_place,
                });
            },
        },
        {
            title: '开始日期',
            dataIndex: 'startTime',
            width: 150,
            render: (text, record) => {
                const { dictObject, onlyRead, disabled } = this.props;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`startTime-${record.id}`}
                            initialValue={text ? moment(text, dateFormat) : null}
                            {...this.commonParams}
                            rules={[{ required: true }]}
                        >
                            <AntdDatePicker
                                disabled={disabled}
                                onChange={value => this.handleFieldChange(value, 'startTime', record.id)}
                            />
                        </AntdFormItem>
                    );
                }
                return <span>{text}</span>;
            },
        },
        {
            title: '结束日期',
            dataIndex: 'endTime',
            width: 150,
            render: (text, record) => {
                const { dictObject, onlyRead, disabled } = this.props;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`endTime-${record.id}`}
                            initialValue={text ? moment(text, dateFormat) : null}
                            {...this.commonParams}
                            rules={[{ required: true }]}
                        >
                            <AntdDatePicker
                                disabled={disabled}
                                onChange={value => this.handleFieldChange(value, 'endTime', record.id)}
                            />
                        </AntdFormItem>
                    );
                }
                return <span>{text}</span>;
            },
        },
        {
            title: '压夜天数',
            dataIndex: 'nightDays',
            width: 100,
            render: (text, record) => {
                const { onlyRead } = this.props;
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`nightDays-${record.id}`}
                            {...this.commonParams}
                            initialValue={text}
                        >
                            <AntdInput disabled={true} placeholder="" />
                        </AntdFormItem>
                    );
                }
                return <span>{text}</span>;
            },
        },
        {
            title: '车次',
            dataIndex: 'trainId',
            width: 180,
            render: (text, record) => {
                const {
                    trainInfo,
                    isHK,
                    dictObject,
                    onlyRead,
                    disabled,
                    trainInfoList,
                    archivesId,
                } = this.props;
                const data = trainInfoList[archivesId] ? trainInfoList[archivesId].list || [] : [];
                if (!onlyRead) {
                    return isHK ? (
                        <AntdFormItem
                            label=" "
                            code={`trainId-${record.id}`}
                            initialValue={text || trainInfo.trainNo}
                            {...this.commonParams}
                        >
                            <AntdInput
                                disabled={true}
                                placeholder=""
                                onChange={value => this.handleFieldChange(value, 'trainId', record.id)}
                            />
                        </AntdFormItem>
                    ) : (
                            <AntdFormItem
                                label=" "
                                code={`trainId-${record.id}`}
                                initialValue={text}
                                {...this.commonParams}
                            >
                                <AdSelect
                                    disabled={disabled}
                                    isExist={true}
                                    data={data.length > 0 ? data.slice(0, data.length - 1) : []}
                                    show={{ id: 'id', name: 'trainNo' }}
                                    onChange={value => this.handleFieldChange(value, 'trainId', record.id)}
                                />
                            </AntdFormItem>
                        );
                }
                return <span>{record.trainNo}</span>;
            },
        },
        {
            title: '司机',
            dataIndex: 'driverIds',
            // width: 150,
            render: (text, record, i) => {
                const { dictObject, onlyRead, disabled, isHK, driversIID } = this.props;
                const { driverIds, driverMap, id } = record;
                const drivers =
                    (driverIds &&
                        driverIds.length > 0 &&
                        driverIds
                            .filter(v => v)
                            .map(v => {
                                return { id: v };
                            })) ||
                    [];
                // console.log(i, 'drivers====', drivers);
                // console.log(i, 'driverMap || drivers=====', driverMap || drivers || []);
                if (!onlyRead) {
                    return (
                        <AntdFormItem
                            label=" "
                            code={`driverIds-${id}`}
                            initialValue={text}
                            {...this.commonParams}
                            //   rules={[{ required: true }]}
                            rules={[{ required: isHK ? true : false }]}
                        >
                            {/* 选择车次后默认带出司机，但还是可以删除，添加，下拉列表带出全部的司机 */}
                            <SearchSelect
                                dataUrl="tms/tms-driver-archives/selectDriverList"
                                url="tms/tms-driver-archives/selectDriverView_s"
                                payload={driversIID}
                                multiple={!isHK} // 是否多选
                                selectedData={driverMap || drivers} // 选中值
                                columns={columnsDriver} // 表格展示列
                                onChange={value => this.handleFieldChange(value, 'driverIds', id, 'driverMap')}
                                id="Archives_pressureInfo_2"
                                disabled={disabled}
                                allowClear={true}
                            />
                        </AntdFormItem>
                    );
                }
                return <span>{record.driverName}</span>;
            },
        },
    ];

    componentWillMount() {
        const { dispatch, archivesId, isHK } = this.props;

        this.saveAllValue({ pressureInfoList: { [archivesId]: { list: [] } } });
        const allDict = [this.state.trainPlace];
        queryDict({ props: this.props, allDict });
    }

    componentDidMount() {
        const { archivesId, pressureInfoList, onRef } = this.props;

        const id = archivesId;
        onRef && onRef(this);
        if (!id) return;
        this.handleStateChange([{ detailId: id }]);
        const detail = pressureInfoList[id];
        // if (detail) return;
        this.pressureInfoList(id);
    }

    componentWillReceiveProps(nextProps, nextState) {
        const { archivesId, pressureInfoList } = nextProps;
        const id = archivesId;
        const { detailId } = nextState;
        if (
            !id &&
            !this.state.detailId &&
            (!detailId || (detailId && detailId === '')) &&
            !pressureInfoList[this.state.detailId]
        ) {
            this.saveAllValue({
                pressureInfoList: { [this.state.detailId]: { list: [this.getAddDataObj()] } },
            });
        }
        if (this.props.archivesId !== id) {
            this.handleStateChange([{ detailId: id }]);
            this.pressureInfoList(id);
        }
    }

    pressureInfoList = (id, payload) => {
        const { dispatch } = this.props;
        dispatch({
            type: allDispatchType.pressureInfoList,
            payload: { id, ...payload },
            callback: data => {
                let newData = data;
                newData.map(v => {
                    if (v.startTime && v.endTime) {
                        v.nightDays = DateMinus(v.startTime, v.endTime);
                    }
                });
            },
        });
    };

    getAddDataObj = () => {
        const { isHK } = this.props;
        const obj = {
            id: `isNew${Math.ceil(Math.random() * 10000) + 10000}`,
            address: '',
            startTime: '',
            endTime: '',
            nightDays: '',
            driverIds: [],
        };
        if (isHK) {
            obj.trainId = this.props.trainInfo.trainId;
            obj.trainNo = this.props.trainInfo.trainNo;
        }
        return obj;
    };

    addInfoPre = () => {
        const { detailId } = this.state;
        let newData = this.getInfoData();
        newData = [this.getAddDataObj(), ...newData];
        this.saveAllValue({ pressureInfoList: { [detailId]: { list: newData } } });
    };

    getInfoData = () => {
        const { pressureInfoList } = this.props;
        const { detailId } = this.state;
        let newData = [];
        if (pressureInfoList[detailId]) {
            const data = pressureInfoList[detailId].list;
            newData = data.map(item => ({ ...item }));
        }
        return newData;
    };

    getRowByKey(id, newData) {
        const data = this.getInfoData();
        return (newData || data).filter(item => item.id === id)[0];
    }

    handleFieldChange(value, fieldName, id, fieldName2) {
        const { detailId } = this.state;
        const { isHK, dispatch, form, showTipsFun, trainInfoList, archivesId } = this.props;
        showTipsFun(true);
        const newData = this.getInfoData();
        const target = this.getRowByKey(id, newData);
        if (!isHK) target.trainNo = ''; //初始化，用于校验
        if (target) {
            target[fieldName] = value;
        }
        if (!target.driverName) {
            target.driverName = '';
        }
        if (fieldName === 'startTime' || fieldName === 'endTime') {
            if (value) {
                target[fieldName] = moment(value).format(dateFormat);
            }
            const days = DateMinus(target.startTime, target.endTime);
            if (target.startTime && target.endTime && days <= 0) {
                target[fieldName] = null;
                target.nightDays = days;
                prompt({ content: '结束日期必须大于开始日期!', type: 'error' });
                this.setState(
                    {
                        preData: target,
                    },
                    () => {
                        form.setFieldsValue({ [`${fieldName}-${target.id}`]: null });
                    }
                );
                return;
            }
            target.nightDays = days;
            this.setState({
                preData: target,
            });
        } else if (fieldName == 'driverIds') {
            target[fieldName] = value.map(v => {
                return v.id;
            });
            target[fieldName2] = value;
            const driverName = value.map(v => {
                return v.name;
            });
            target.driverName = driverName.join(',');
        } else if (!isHK && fieldName == 'trainId') {
            const trainData = trainInfoList[archivesId] ? trainInfoList[archivesId].list || [] : [];
            const targetTrain = trainData.filter(v => v.id == value);
            target.trainNo = targetTrain[0] ? targetTrain[0].trainNo : '';
            target[fieldName] = targetTrain[0] ? targetTrain[0].id : '';
            // 压夜选择车次后，默认带出当前车次的司机，如当前压夜记录已有司机，则保留原来值
            console.log('target.driverName', target.driverName);
            if (!target.driverName) {
                target.driverMap = targetTrain[0] ? targetTrain[0].driverMap : [];
                target.driverIds = target.driverMap.map(v => {
                    return v.id;
                });
                const driverName = target.driverMap.map(v => {
                    return v.name;
                });
                target.driverName = driverName.join(',');
            }
        }
        // console.log('newData', newData);

        this.saveAllValue({ pressureInfoList: { [detailId]: { list: newData } } });
    }

    saveAllValue = payload => {
        const { dispatch } = this.props;
        dispatch({
            type: allDispatchType.value,
            payload: payload || {},
        });
    };

    handleStateChange = (options = []) => {
        options.map(item => {
            this.setState(item);
        });
    };

    render() {
        const {
            pressureInfoList,
            loading,
            onSelectRow,
            selectedRows,
            archivesId,
            disabled,
        } = this.props;
        const { detailId } = this.state;
        const data = pressureInfoList[detailId] || {};
        return (
            <div className={styles.customPartsOfferInfo}>
                <AntdForm>
                    <StandardTable
                        loading={loading}
                        data={data}
                        columns={this.columns}
                        selectedRows={selectedRows}
                        disabledRowSelected={disabled}
                        pagination={false}
                        scrollX={900}
                        scrollY={200}
                        canInput={true}
                        onSelectRow={selectedRows => {
                            onSelectRow(selectedRows);
                        }}
                    />
                </AntdForm>
            </div>
        );
    }
}
